package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private AdminFeign adminFeign;
    @Autowired
    private AuthorMapper authorMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private GeneratePageServiceImpl generatePageService;
    /**
     * 文章自动发布
     * @param newsId 文章id
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class, timeoutMills = 100000)
    public void publishArticle(Integer newsId) {
        //1.校验参数
        if (newsId ==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ResponseResult<WmNews> responseResult = wemediaFeign.findWmNewsById(newsId);
        WmNews wmNews = responseResult.getData();
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //1.2 判断文章状态
        if (wmNews.getStatus()!=4&&wmNews.getStatus()!=8) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章审核未通过");
        }

        //2. 保存文章到文章发布表
        ApArticle apArticle = saveArticleByWmNews(wmNews,newsId);

        //3.保存配置表、保存内容表
        Boolean flag2 = saveConfigAndContent(wmNews,apArticle);
        if (!flag2) {
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"内容，配置信息保存失败");
        }

        //4.TODO 页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),apArticle);

        //5.更新wmNews状态为9，添加article_Id
        updateWmNews(wmNews,apArticle,newsId);


        //6. TODO 通知ES索引库添加文章索引



    }


    @Autowired
    private ApArticleMapper apArticleMapper;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Value("${file.minio.readPath}")
    String readPath;
    /**
     * 根据参数加载文章列表
     * @param loadtype 0为加载更多  1为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        //1 参数检查
        // 页大小
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        dto.setSize(size);
        // 频道
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        // 时间
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        // 类型判断
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //2 执行查询
        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, loadtype);
        for (ApArticle article : articleList) {
            // 获取文章封面字段
            String images = article.getImages();
            if (StringUtils.isNotBlank(images)) {
                // 将封面按照,号切割   生成流
                images = Arrays.stream(images.split(","))
                        // 每一个路径添加前缀
                        .map(url -> webSite + url)
                        // 将加了前缀的路径  拼接成字符串
                        .collect(Collectors.joining(","));
                article.setImages(images);
            }

            article.setStaticUrl(readPath + article.getStaticUrl());
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(articleList);
        return result;
    }

    private void updateWmNews(WmNews wmNews, ApArticle apArticle, Integer newsId) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(apArticle.getId());
        ResponseResult result = wemediaFeign.updateWmNews(wmNews);
        if (!result.checkCode()) {
            log.error("文章发布失败 远程调用修改文章接口失败， 不予发布 , 文章id : {} ",newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用修改文章接口失败");
        }
    }

    private Boolean saveConfigAndContent(WmNews wmNews,ApArticle apArticle) {
        Boolean flag = false;

        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        int i1 = apArticleConfigMapper.insert(apArticleConfig);

        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        int i = apArticleContentMapper.insert(apArticleContent);

        if (i1 ==1 && i==1) {
            flag = true;
        }
        return flag;
    }

    /**
     * 保存文章到发布表
     * @param wmNews
     * @return
     */
    private ApArticle saveArticleByWmNews(WmNews wmNews,Integer newsId) {


        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(wmNews,apArticle);
        //设置封面类型 名字不同的字段
        apArticle.setLayout(wmNews.getType());

        //获取作者信息、频道信息，并设置到发布表
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        Integer id = apAuthor.getId();
        String name = apAuthor.getName();
        apArticle.setAuthorId(Long.valueOf(id));
        apArticle.setAuthorName(name);

        ResponseResult<AdChannel> responseResult = adminFeign.findOne(wmNews.getChannelId());
        if (!responseResult.checkCode()) {
            log.error("文章发布失败 远程调用查询频道接口失败， 不予发布 , 文章id : {} ",newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用修改文章接口失败");
        }

        AdChannel adChannel = responseResult.getData();
        String name1 = adChannel.getName();
        apArticle.setChannelName(name1);

        // 判断wmNews之前是否关联 articleId
        if(apArticle.getId() == null){
            // 无关联  新增 article
            // 保存文章
            apArticle.setCollection(0); // 收藏数
            apArticle.setLikes(0);// 点赞数
            apArticle.setComment(0);// 评论数
            apArticle.setViews(0); // 阅读数
            if (!this.save(apArticle)) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"保存发布表失败");
            }
        }else {
            // 有关联  修改 article
            // 修改文章  删除之前关联的配置信息   内容信息
            ApArticle article = getById(apArticle.getId());
            if(article == null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的文章不存在");
            }
            updateById(apArticle);
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId,apArticle.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId,apArticle.getId()));
        }

        return apArticle;
    }
}